package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupAndItemMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.itheima.common.utils.PageUtil.setDefaultIfNullOrZero;

@Service
public class CheckItemServiceImpl implements CheckItemService {

    @Autowired
    private CheckItemMapper checkItemMapper;

    @Autowired
    private CheckGroupAndItemMapper checkGroupAndItemMapper;

    /**
     * 新增检查项目
     *
     * @param checkItem
     */
    @Override
    public void add(CheckItem checkItem) {
        checkItemMapper.add(checkItem);
    }

    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        setDefaultIfNullOrZero(queryPageBean.getPageSize(), 10, queryPageBean::setPageSize);
        setDefaultIfNullOrZero(queryPageBean.getCurrentPage(), 1, queryPageBean::setCurrentPage);
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckItem> page = checkItemMapper.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }
    /**
     * 根据id查询检查项目
     *
     * @param id
     * @return
     */
    @Override
    public CheckItem findById(Integer id) {
        return checkItemMapper.findById(id);
    }

    /**
     * 根据id修改检查项目
     *
     * @param checkItem
     */
    @Override
    public void updataById(CheckItem checkItem) {
        checkItemMapper.updataById(checkItem);
    }

    /**
     * 查询所有检查项目
     *
     * @return
     */
    @Override
    public List<CheckItem> findAll() {
        return checkItemMapper.findAll();
    }

    /**
     * 根据检查组id查询检查项id集合
     *
     * @param checkGroupId
     * @return
     */
    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer checkGroupId) {
        return checkGroupAndItemMapper.findCheckItemIdsByCheckGroupId(checkGroupId);
    }

    /**
     * 根据id删除检查项
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        List<Map<String, Object>> result = checkGroupAndItemMapper.selectByCheckItemId(id);
        if (Objects.nonNull(result) && !result.isEmpty()) {
            throw new RuntimeException("当前检查项被检查组关联，不能删除");
        }
        checkItemMapper.deleteById(id);
    }
}
